package com.lizi.core.httpclient;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpPostTest {

	public static String rest(String url,Map<String,String> params){ 
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();

			HttpPost httpPost = new HttpPost(url);
			if(params!=null && params.size()>0){
				List <NameValuePair> nvps = new ArrayList <NameValuePair>();
				Iterator<String> keys = params.keySet().iterator();
				while(keys.hasNext()){
					String key = keys.next();
					nvps.add(new BasicNameValuePair(key, params.get(key)));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(nvps,Charset.forName("UTF-8")));
			}
//			httpPost.addHeader("Content-type","application/json; charset=utf-8");
//
//			httpPost.setHeader("Accept", "application/json");

	 
			 
			CloseableHttpResponse response = httpclient.execute(httpPost);

			try {
			    //System.out.println(response.getStatusLine());
			    HttpEntity entity = response.getEntity();
			    // do something useful with the response body
			    // and ensure it is fully consumed
			    return EntityUtils.toString(entity);
			    //EntityUtils.consume(entity);
			} finally {
			    response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
		
	}
	
	
	public static void main(String[] args)  {
		String data = HttpPostTest.rest("http://www-dev.lizi.com/logistics/callback", null);
		System.out.println(data);
	}
}
